package com.glodon.paas.account.security.oauth1.service;

import com.glodon.paas.account.api.oauth1.AccessTokenInfo;
import com.glodon.paas.account.api.oauth1.AccessValidationRequest;
import com.glodon.paas.account.api.oauth1.AccessValidationResponse;
import com.glodon.paas.account.api.oauth1.Parameter;
import com.glodon.paas.account.dao.domain.OAuthTokenEntity;
import com.glodon.paas.account.security.oauth1.provider.OAuthTokenManager;
import com.glodon.paas.account.security.oauth1.provider.SimpleOAuthProvider;
import com.glodon.paas.exception.PaasServerExceptionFactory;
import net.oauth.OAuth;
import net.oauth.OAuthAccessor;
import net.oauth.OAuthException;
import net.oauth.OAuthMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.List;

/**
 * Validate the access to resource servers
 *
 * @author Don Li
 */
@Component
@Path("/validation")
public class AccessValidationService {
    private static final Logger LOGGER = LoggerFactory.getLogger(AccessValidationService.class);

    @Autowired
    private SimpleOAuthProvider oauthProvider;

    @POST
    @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    @Produces(MediaType.APPLICATION_JSON)
    public AccessValidationResponse validate(AccessValidationRequest request) {

        List<OAuth.Parameter> parameters = new ArrayList<OAuth.Parameter>();
        for (OAuth.Parameter parameter : OAuthMessage.decodeAuthorization(request.getAuthorization())) {
            if (!"realm".equalsIgnoreCase(parameter.getKey())) {
                parameters.add(parameter);
            }
        }
        List<Parameter> otherParams = request.getParams();
        if (otherParams != null) {
        	for (Parameter param : otherParams) {
                parameters.add(new OAuth.Parameter(param.getKey(), param.getValue()));
            }
        }
        
        OAuthMessage message = new OAuthMessage(request.getMethod(), request.getUrl(), parameters);

        LOGGER.debug("do validation for: {}", message.toString());
        try {
            OAuthAccessor accessor = oauthProvider.getAccessor(message);
            oauthProvider.VALIDATOR.validateMessage(message, accessor);
            return new AccessValidationResponse(oauthProvider.getRealm(), (String) accessor.getProperty("user"), accessor.consumer.consumerKey, null, true);
        } catch (OAuthException e) {
            return new AccessValidationResponse(oauthProvider.getRealm(), false);
        } catch (Exception e) {
            LOGGER.error("fail to validate access", e);
            return new AccessValidationResponse(oauthProvider.getRealm(), false);
        }

    }

    //TODO
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public AccessTokenInfo getAccessTokenInfo(@QueryParam("access_token") String accessToken) {
        if (accessToken == null || "".equals(accessToken)) {
            return new AccessTokenInfo();
        }
        OAuthTokenManager tokenManager = oauthProvider.getTokenMgr();
        try {
            OAuthTokenEntity token = tokenManager.getToken(accessToken);
            throw PaasServerExceptionFactory.unImplementedException("", null);
//            return new AccessTokenInfo(token.getConsumerKey());
        } catch (OAuthException e) {
            return new AccessTokenInfo();
        }
    }
}
